package com.cool;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

/**
 * Created by Administrator on 2017/11/2.
 */

public class HibernateUtil {

    private static StandardServiceRegistry registry;
    private static SessionFactory sessionFactory;

    static {
        if (sessionFactory == null){
            registry = new StandardServiceRegistryBuilder().configure().build();
            MetadataSources metadataSources = new MetadataSources(registry);
            try {
                sessionFactory = metadataSources.buildMetadata().buildSessionFactory();
            }catch (Exception  e){
                e.printStackTrace();
                StandardServiceRegistryBuilder.destroy(registry);
            }

        }
    }

    public static Session openSession(){
        return sessionFactory.openSession();
    }

    public static void closeSession(Session session){
        try {
            if (session != null){
                sessionFactory.close();
            }
        }catch (HibernateException e){
            e.printStackTrace();
        }
    }
}
